package com.hspedu.houserent.service;

import com.hspedu.houserent.domain.House;
import com.hspedu.houserent.utils.Utility;

/**
 * 名称HouseService
 * 描述[业务层] 响应HouseView的调用，完成对房屋信息的各种操作，增删改查crud
 *
 * @version 1.0
 * @author:zschun
 * @datatime:2023-02-07 12:12
 */
public class HouseService {

    private House[] houses;//保存houses对象
    private int houseNums = 1;
    private int idCounter = 1;

    //构造器
    public HouseService(int size) {
        houses = new House[size];//创建HouseService对象，指定数组大小

        houses[0] = new House(1, "朱琴", "1210", "仁和小区", 860, "未出租");
    }

    public House[] list() {
        return houses;
    }

    public boolean add(House newHouse) {
        if (houseNums >= houses.length) {
            System.out.println("已达到房屋数量限制！！！");
            return false;
        }
        houses[houseNums++] = newHouse;
        newHouse.setId(++idCounter);
        return true;
    }

    public boolean del(int delId) {
        int index = -1;

        for (int i = 0; i < houseNums; i++) {
            if (delId == houses[i].getId()) {
                index = i;
            }
        }

        if (index == -1) {
            System.out.println("您输入的房屋编号不存在！！！");
            return false;
        }

        for (int i = index; i < houseNums - 1; i++) {
            houses[i] = houses[i+1];
        }
        houses[--houseNums] = null;

        return true;
    }

    public boolean search(int searchId) {
        int index = -1;
        for (int i = 0; i < houseNums; i++) {
            if (searchId == houses[i].getId()) {
                System.out.println(houses[i]);
                index = i;

                return true;
            }
        }

        if (index == -1) System.out.println("您查找的房屋编号不存在...");
        return false;
    }

    public boolean change(int changeId) {
        int flag = -1;
        for (int i = 0; i < houseNums; i++) {
            if (changeId == houses[i].getId()) {

                flag = i;

                System.out.print("姓名("+houses[flag].getName()+")：");
                String newName = Utility.readString(10);
                houses[flag].setName(newName);
                System.out.print("电话("+houses[flag].getPhone()+")：");
                String newPhone = Utility.readString(10);
                houses[flag].setPhone(newPhone);
                System.out.print("地址("+houses[flag].getAddress()+")：");
                String newAddress = Utility.readString(10);
                houses[flag].setAddress(newAddress);
                System.out.print("租金("+houses[flag].getRent()+")：");
                int newRent = Utility.readInt();
                houses[flag].setRent(newRent);
                System.out.print("状态("+houses[flag].getState()+")：");
                String newState = Utility.readString(10);
                houses[flag].setState(newState);

                return true;
            }
        }

        if (flag == -1) System.out.println("您查找的房屋编号不存在，修改失败...");
        return false;
    }
}
